/*
 * FileName: virtual_vfptr.cc
 * Author: 李波(Edwin Lee)
 * Date: 2024-06-04 16:43:35
 * Version: 1.0
 * Description: 虚函数表vftable地址写入vfptr的时间
 */
#include <iostream>
#include <string.h>
using namespace std;

class Base 
{
	public:
		Base()
		{//有虚函数的类，会在构造函数开始的位置把虚函数表vftable的指针写入虚指针vfptr
			cout<<"call Base()"<<endl;
			clear();
		}

		void clear()
		{
			memset(this,0,sizeof(*this));
		}

		virtual void show()
		{
			cout<<"call Base::show"<<endl;
		}
};

class Derive:public Base
{
	public:
		Derive()
		{//派生类构造函数会重写vfptr，所以基类clear()对派生类没有影响
			cout<<"call Derive()"<<endl;
		}
		void show()
		{
			cout<<"call Derive::show"<<endl;
		}
};

int main()
{
	/*
	//这段代码由于Base构造函数中clear()清零了虚函数表，所有会出错
	Base *p1 = new Base();
	p1->show();
	delete p1;
	*/
	//这段代码由于Derive构造函数中重写了vfptr，所以不会出错
	Base *p2 = new Derive();
	p2->show();
	delete p2;
	return 0;
}
